package com.griddroid.activities;

import com.griddroid.configuration.GridConfig;
import com.griddroid.nodes.GridServer;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ScrollView;

/**
 * An activity that runs on the server node. It includes a {@link GridServer
 * GridServer} to carry out all the important grid tasks. The activity itself
 * just has a {@link LogTextBox LogTextBox} to output all the debug messages.
 * 
 * @author Charalampos Mavroforakis
 * @author Thomas Ailianos
 * @author Michail Michailidis
 * 
 */
public class Server extends Activity
{
	LogTextBox tv;
	ScrollView sv;
	GridServer server;

	/**
	 * Called when the activity is first created. It initializes the
	 * {@link GridServer GridServer} and sets its {@link #messagehandler
	 * messageHandler}.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		tv = new LogTextBox(this);
		sv = new ScrollView(this);
		sv.addView(tv);
		setContentView(sv);
		server = new GridServer();
		server.setHandler(messagehandler);
		server.start();
	}

	/**
	 * This is the handler responsible for any messages from the included grid
	 * server
	 */
	public Handler messagehandler = new Handler()
	{
		/**
		 * It has been overridden, so that it will handle the custom messages
		 * accordingly. Through this method, the handler will print messages on
		 * the view (debug information)
		 * 
		 * @param msg
		 *            a message from the GridServer. Its {@link Message#what
		 *            'what' attribute} is set according to the
		 *            {@link GridConfig GridConfig configuration}, denoting the
		 *            purpose of the message. The only message type that really
		 *            matters is the {@link GridConfig#UPDATE_TEXTVIEW
		 *            UPDATE_TEXTVIEW}
		 * 
		 */
		@Override
		public void handleMessage(Message msg)
		{
			if (msg.what == GridConfig.UPDATE_TEXTVIEW)
			{
				tv.append((String) msg.obj + "\n");
				sv.fullScroll(View.FOCUS_DOWN);
			}
			else if (msg.what == GridConfig.CLOSE)
			{
			}
		}
	};

	/**
	 * Overridden method to handle the press of the Back Button on the mobile
	 * device. It will shutdown the server and destroy the whole grid eventually
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent ev)
	{

		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			if (server != null)
			{
				server.close();
				server = null;
				this.finish();
			}
			return true;
		}
		return false;
	}
}